const mysql = require('mysql')
const config = require('./defaultConfig.js')

// 创建线程池
let pool = mysql.createPool({
    host: config.dataBase.HOST,
    user: config.dataBase.USERNAME,
    password: config.dataBase.PASSWORD,
    database: config.dataBase.DATABASE,
    port: config.dataBase.PORT,
})

// 连接线程池，做SQL查找 
let allServices = {
    query: function (sql, value) {
        return new Promise((resolve, reject) => {
            pool.getConnection(function (err, connection) {
                if (err) {
                    console.log('与MySQL数据库建立连接失败');
                    reject(err)
                } else {
                    console.log('与MySQL数据库建立连接成功');
                    connection.query(sql, value, (err, rows) => {
                        if (err) {
                            console.log('查询失败', err);
                            reject(err)
                        }
                        else {
                            resolve(rows)
                        }
                        connection.release()
                    })
                }
            })
        })
    }
}

module.exports = {
    allServices
}